<?php
/**
 * 打包管理
 * @author hanxiaojun
 *
 */
class PackageControl extends CommonControl{
	
	function listAction(){
		//$this->page_size = 5;
		$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
		$page = is_numeric($page) ? ($page > 0 ? $page : 1) : 1;
		
		$user_id = $this->user_info['user_id'];
		if($this->user_info['is_admin'] != 1){
			$user_sql = " and user_id={$user_id}";
		}
		
		$package_model = D('package');
		
		// 获取地区
		$channel_country = $package_model->getChannelCountry();
		$this->out['channel_country'] = $channel_country;
		
		$is_search = $_REQUEST['is_search'];
		if($is_search == 1){
			$channel_id = trim($_REQUEST['channel_id']);
			$area_num = trim($_REQUEST['area']);
			if(empty($channel_id)){
				$channel_sql = "";
			}else{
				$channel_sql = " and channel_id='{$channel_id}'";
			}
			if(empty($area_num)){
				$area_sql = '';
			}else{
				$area_sql = " and channel_area='{$area_num}'";
			}
			$this->out['channel_id'] = $channel_id;
			$this->out['area_num'] = $area_num;
		}
		
		
		
		$sql = "select channel_id,user_id,channel_coo,channel_area,channel_option,is_bind,is_download_url,addtime from channel_list where 1=1 {$user_sql} {$channel_sql} {$area_sql} order by addtime desc";
		
		$array = $package_model->db->getRecordsByPage($page, $this->page_size, $sql);
		$data = $array['data'];
		//处理数据
		if(empty($data)){
			$data = array();
		}
		foreach ($data as $kd=>$vd){
			$channel_area = $vd['channel_area'];
			$data[$kd]['country_cn'] = '';
			foreach ($channel_country as $kcc=>$vcc){
				if($vcc['country_num'] == $channel_area){
					$data[$kd]['country_cn'] = $vcc['country_cn'];
					break;
				}
			}
			//获取用户角色
			$role_info = $package_model->getUserRole($vd['user_id']);
			$data[$kd]['role_name'] = $role_info['role_name'];
			$data[$kd]['user_name'] = $role_info['user_name'];
			//获取推广地址
			$channel_id = $vd['channel_id'];
			$data[$kd]['channel_url'] = $package_model->getChannelUrlInfo($channel_id);
		}
		
		
		$this->out['pageCount'] = $array['pageCount'];
		$this->out['page'] = $array['page'];
		$this->out['pageDisplay'] = $this->pageDisplay;
		$this->out['data'] = $data;
		$this->out['is_admin'] = $this->user_info['is_admin'];
		$this->out['href'] = DOMAIN . '?act=package.list&area='.$area_num;
		$this->out['pagestring'] = $this->fetch("all.pages.html");
		$this->display('package.list.html');
	}
	
	// 添加打包渠道页面
	function addAction(){
		$package_model = D('package');
		// 获取地区
		$channel_country = $package_model->getChannelCountry();
		$this->out['channel_country'] = $channel_country;
		$this->display('package.add.html');
	}
	function insertAction(){
		//versoion_type	1-->pro 0-->lite
		//area 999-全球  886-台湾
		//Array ( [version_type] => 1 [area] => 0 [is_bind] => 0 [bind_package] => [is_install] => 0 [sub_channel] => 0 [download_url] => [submit] => 保存 )
		$re_arr = array();
		$insert_channel_arr = array();
		$insert_channel_url_arr = array();
		$channel_coo = trim($_POST['channel_coo']);
		$version_type = trim($_POST['version_type']);
		$version_type = empty($version_type)?'1':$version_type;
		$area = trim($_POST['area']);
		$area = empty($area)?'999':$area;
		$area = sprintf("%03d",$area);
		//绑定
		$is_bind = trim($_POST['is_bind']);
		$is_bind = empty($is_bind)?0:1;
		//预装
		$is_install = trim($_POST['is_install']);
		$is_install = empty($is_install)?0:1;
		//接入方式
		$join_type = trim($_POST['join_type']);
		$join_type = empty($join_type)?0:1;
		
		$bind_package = $_POST['bind_package'];
		if($is_bind == 1){
			//没有去除数组中的空值
			$bind_package = array_unique($bind_package);
			//去除数组中的空字符
			foreach ($bind_package as $kbp=>$vbp){
				$vbp = trim($vbp);
				if(empty($vbp)){
					unset($bind_package[$kbp]);
				}
			}
			if(empty($bind_package)){
				//软件包名为空
				$re_arr['status'] = 2;
				echo json_encode($re_arr);
				return false;
			}
		}
		
		//组合二进制数
		$binary = $is_install.$is_bind.$join_type.'000';
		$decade = bindec($binary);
		$decade_str=sprintf("%02d",$decade);
		//子渠道号
		$channel_min = $this->user_info['channel_min'];
		$channel_max = $this->user_info['channel_max'];
		if($channel_min < 0 || empty($channel_max)){
			//子渠道号为空，重新登录
			unset($_SESSION['user']);
			$re_arr['status'] = 3;
			echo json_encode($re_arr);
			return false;
		}
		
		$package_model = D('package');
		
		for($sub_channel = $channel_min;$sub_channel <= $channel_max;$sub_channel++){
			//组合成渠道号
			$sub_channel_str = sprintf("%04d",$sub_channel);
			$channel_id = "".$version_type.$area.$decade_str.$sub_channel_str;
			$check_channel = $package_model->checkChannel($channel_id);
			if(!$check_channel){
				break;
			}else{
				$channel_id = '';
			}
		}
		//渠道号已经被占用完
		if(empty($channel_id)){
			$re_arr['status'] = 4;
			echo json_encode($re_arr);
			return false;
		}
		
		//开始执行打包命令
		/*
		 * 不捆绑的渠道包命令
		 * java -jar /work/android_package/package/1MobileAutoPackage.jar /work/android_package/market_apk/1MobileMarket_tw.apk /work/android_package/market_package -c 8888
		 * 
		 * 捆绑软件的渠道包命令
		 * java -jar /work/android_package/package/1MobileAutoPackage.jar /work/android_package/market_apk/1MobileMarket_tw.apk /work/android_package/market_package -c 8888 -b com.kimi.ggplay.txjntw_om com.kimi.ggplay.txjntw_om_tw_quickdownload_8888.apk
		 * 
		 */
		//运营推广地址
		$package_coo_url = C('package_coo_url');
		
		//一、打包程序
		$package_jar_path = C('package_jar_path');
		$package_market_path = C('package_market_path');
		$package_cmd = "java -jar {$package_jar_path} {$package_market_path}";
		//二、market安装源文件
		//获取地区额配置信息(全球和台湾，以后会增加其他地区)
		
		$area_config = $package_model->getChannelCountryByNum($area);
		if(empty($area_config)){
			$area = '999';
			$area_config = $package_model->getChannelCountryByNum($area);
		}
		
		$market_lang_path = $area_config['market_lang']."/";
		$market_package = $area_config['market_name'];
		$market_package_apk = "{$market_package}.apk";
		$package_download_url = $area_config['market_domain'];
		
		
		$package_cmd .= $market_package_apk;
		//三、输出路径
		$package_out_path = C('package_out_path');
		//默认的线上下载地址目录
		$package_default_domain = C('package_default_domain');
		//此处要定义输入路径规则,用子渠道号来定义目录
		$package_out_path .= $market_lang_path.$sub_channel_str;
		//线上下载地址目录
		$package_online_dir = $package_default_domain.$market_lang_path.$sub_channel_str;
		
		
		//创建目录
		make_dir($package_out_path);
		
		$package_cmd .= ' '.$package_out_path;
		//默认内部包名
		$package_name = 'com.onemobile';
		//给要插入的数据赋值
		$insert_channel_arr['channel_id'] = $channel_id;
		$insert_channel_arr['user_id'] = $this->user_info['user_id'];
		$insert_channel_arr['channel_coo'] = $channel_coo;
		$insert_channel_arr['channel_sub'] = $sub_channel_str;
		$insert_channel_arr['channel_area'] = $area;
		$insert_channel_arr['channel_option'] = $binary;
		$insert_channel_arr['version_type'] = $version_type;
		$insert_channel_arr['is_bind'] = $is_bind;
		$insert_channel_arr['addtime'] = time();
		
		//---------一、如果直接输入下载地址，就不用打包，直接生成推广地址就可以。--------
		$web_download_url = trim($_POST['download_url']);
		if(!empty($web_download_url)){
			//填写直接下载状态
			$insert_channel_arr['is_download_url'] = 1;
			//数据库中插入数据
			$insert_channel_url_arr['channel_id']=$channel_id;
			$insert_channel_url_arr['package_name']=$package_name;
			//推广运营地址
			$insert_coo_url = $package_coo_url.$package_name."/".$channel_id."/";
			$insert_channel_url_arr['coo_url'] = $insert_coo_url;
			$insert_download_url = $web_download_url;
			$insert_channel_url_arr['download_url']=$insert_download_url;
			$insert_channel_url_arr['addtime']=time();
			M()->db->insert('channel_list',$insert_channel_arr);
			M()->db->insert('channel_url',$insert_channel_url_arr);
			
			//将下载地址存储到reids中
			$this->saveRedis($channel_id, $package_name, $web_download_url);
			
			//ajax信息输出
			$re_arr['status'] = 1;
			$re_arr['coo_url'] = array($insert_coo_url);
			echo json_encode($re_arr);
			return false;
		}
		
		//-----------二、捆绑不绑定软件的market安装包-------------
		//定义单独的执行命令
		$exec_cmd = "";
		if($is_bind == 0){
			$exec_cmd = $package_cmd.' -c '.$channel_id;
			
			exec($exec_cmd.' >> /tmp/package_admin.log');
			
			//数据库中插入数据
			$insert_channel_url_arr['channel_id']=$channel_id;
			$insert_channel_url_arr['package_name']=$package_name;
			//推广运营地址
			$insert_coo_url = $package_coo_url.$package_name."/".$channel_id."/";
			$insert_channel_url_arr['coo_url'] = $insert_coo_url;
			$insert_download_url = $package_online_dir.'/'.$market_package.'_'.$channel_id.'.apk';
			$insert_channel_url_arr['download_url']=$insert_download_url;
			$insert_channel_url_arr['addtime']=time();
			
			M()->db->insert('channel_list',$insert_channel_arr);
			M()->db->insert('channel_url',$insert_channel_url_arr);
			
			//将下载地址存储到reids中
			$this->saveRedis($channel_id, $package_name, $insert_download_url);
			
			//ajax信息输出
			$re_arr['status'] = 1;
			$re_arr['channel_id'] = $channel_id;
			$re_arr['coo_url'] = array($insert_coo_url);
			echo json_encode($re_arr);
			return false;
		}elseif($is_bind == 1){
			//-----------------三、捆绑绑定其他软件的market安装包------------------------
			//ajax信息输出
			$re_arr['status'] = 1;
			$coo_url_arr = array();
			//首先插入channel_list渠道号
			M()->db->insert('channel_list',$insert_channel_arr);
			
			foreach ($bind_package as $package_name){
				$insert_channel_url_arr = array();
				//-c 8888 -b com.kimi.ggplay.txjntw_om com.kimi.ggplay.txjntw_om_tw_quickdownload_8888.apk
				$exec_cmd = $package_cmd.' -c '.$channel_id.' -b '.$package_name.' '.$package_name.'_quickdownload_'.$channel_id.'.apk';
				exec($exec_cmd.' >> /tmp/package_admin.log');
				//数据库中插入数据
				$insert_channel_url_arr['channel_id']=$channel_id;
				$insert_channel_url_arr['package_name']=$package_name;
				//推广运营地址
				$insert_coo_url = $package_coo_url.$package_name."/".$channel_id."/";
				$insert_channel_url_arr['coo_url'] = $insert_coo_url;
				$insert_download_url = $package_online_dir.'/'.$package_name.'_quickdownload_'.$channel_id.'.apk';
				$insert_channel_url_arr['download_url']=$insert_download_url;
				$insert_channel_url_arr['addtime']=time();
				M()->db->insert('channel_url',$insert_channel_url_arr);
				
				//将下载地址存储到reids中
				$this->saveRedis($channel_id, $package_name, $insert_download_url);
				
				$coo_url_arr[] = $insert_coo_url;
			}
			$re_arr['channel_id'] = $channel_id;
			$re_arr['coo_url'] = $coo_url_arr;
			echo json_encode($re_arr);
			return false;
		}
	}
	
	
	function updateAction(){
		$channel_id = trim($_GET['channel_id']);
		if(empty($channel_id)){
			$this->alert('没有渠道号');
			return false;
		}
		$package_model = D('package');
		$channel_list_info = $package_model->getChannelListInfo($channel_id);
		$channel_url_info = $package_model->getChannelUrlInfo($channel_id);
		
		$this->out['channel_list_info'] = $channel_list_info;
		$this->out['channel_url_info'] = $channel_url_info;
		
		$this->display('package.edit.html');
	}
	
	function doupdateAction(){
		$re_arr = array();
		$update_channel_list = array();
		$update_channel_url = array();
		$channel_id = trim($_POST['channel_id']);
		if(empty($channel_id)){
			$re_arr['status'] = 2;
			echo json_encode($re_arr);
			return false;
		}
		
		//判断这个渠道号是否属于这个用户，以及原来渠道的状态
		$package_model = D('package');
		$channel_info_old = $package_model->getChannelListInfo($channel_id);
		if($channel_info_old['user_id'] != $this->user_info['user_id']){
			$re_arr['status'] = 2;
			echo json_encode($re_arr);
			return false;
		}
		//如果这个渠道既不捆绑也不下载不允许修改
		/* if($channel_info_old['is_bind'] == 0 && $channel_info_old['is_download_url'] == 0){
			$re_arr['status'] = 3;
			echo json_encode($re_arr);
			return false;
		} */
		
		//默认内部包名
		$package_name = "com.onemobile";
		
		//子渠道号
		$sub_channel_str = $channel_info_old['channel_sub'];
		
		$bind_package = $_POST['bind_package'];
		$channel_coo = trim($_POST['channel_coo']);
		$download_url = trim($_POST['download_url']);
		//如果填写了下载地址，直接使用下载地址
		if(!empty($download_url)){
			
			$update_channel_url['download_url'] = $download_url;
			$package_model->db->updateRecord('channel_url',"channel_id='{$channel_id}'",$update_channel_url);
			
			//将下载地址存储到reids中
			$this->saveRedis($channel_id, $package_name, $download_url);
			$update_channel_list['channel_coo'] = $channel_coo;
			$update_channel_list['is_bind'] = 0;
			$update_channel_list['is_download_url'] = 1;
			$package_model->db->updateRecord('channel_list',"channel_id='{$channel_id}'",$update_channel_list);
			$re_arr['status'] = 5;
			echo json_encode($re_arr);
			return false; 
		}else{
			//没有去除数组中的空值
			$bind_package = array_unique($bind_package);
			//去除数组中的空字符
			foreach ($bind_package as $kbp=>$vbp){
				$vbp = trim($vbp);
				if(empty($vbp)){
					unset($bind_package[$kbp]);
				}
			}
			if(empty($bind_package)){
				//软件包名为空
				$re_arr['status'] = 4;
				echo json_encode($re_arr);
				return false;
			}
			//执行自动打包命令，更新数据库
			//获取打包的配置文件
			$area_config = $package_model->getChannelCountryByNum($channel_info_old['channel_area']);
			if(empty($area_config)){
				$area = '999';
				$area_config = $package_model->getChannelCountryByNum($area);
			}
			$market_lang_path = $area_config['market_lang']."/";
			$market_package = $area_config['market_name'];
			$market_package_apk = "{$market_package}.apk";
			$package_download_url = $area_config['market_domain'];
			
			
			//运营推广地址
			$package_coo_url = C('package_coo_url');
			//一、打包程序
			$package_jar_path = C('package_jar_path');
			$package_market_path = C('package_market_path');
			$package_cmd = "java -jar {$package_jar_path} {$package_market_path}";
			
			$package_cmd .= $market_package_apk;
			//三、输出路径
			$package_out_path = C('package_out_path');
			//默认的线上下载地址目录
			$package_default_domain = C('package_default_domain');
			//此处要定义输入路径规则,用子渠道号来定义目录
			$package_out_path .= $market_lang_path.$sub_channel_str;
			//线上下载地址目录
			$package_online_dir = $package_default_domain.$market_lang_path.$sub_channel_str;
			
			//组合打包命令
			
			$package_cmd .= ' '.$package_out_path;
			
			//首先删除下载地址，然后重新插入
			$del_sql = "delete from channel_url where channel_id='{$channel_id}'";
			$package_model->execute($del_sql);
			
			foreach ($bind_package as $package_name){
				$insert_channel_url_arr = array();
				//-c 8888 -b com.kimi.ggplay.txjntw_om com.kimi.ggplay.txjntw_om_tw_quickdownload_8888.apk
				$exec_cmd = $package_cmd.' -c '.$channel_id.' -b '.$package_name.' '.$package_name.'_quickdownload_'.$channel_id.'.apk';
				
				//$exec_cmd_arr[] = $exec_cmd;
				
				//判断数据库中是否存在,不存在然后生成
				//$channel_id_check = $package_model->checkChannelExists($channel_id,$package_name);
				//判断打包文件是否存在
				$package_file_path = $package_out_path.'/'.$package_name.'_quickdownload_'.$channel_id.'.apk';
				if(!file_exists($package_file_path)){
					exec($exec_cmd.' >> /tmp/package_admin.log');
				}
				//线上推广运营地址
				$insert_coo_url = $package_coo_url.$package_name."/".$channel_id."/";
				//数据库中插入数据
				$insert_channel_url_arr['channel_id']=$channel_id;
				$insert_channel_url_arr['package_name']=$package_name;
				//推广运营地址
				$insert_channel_url_arr['coo_url'] = $insert_coo_url;
				$insert_download_url = $package_online_dir.'/'.$package_name.'_quickdownload_'.$channel_id.'.apk';
				$insert_channel_url_arr['download_url']=$insert_download_url;
				$insert_channel_url_arr['addtime']=time();
				$package_model->db->insert('channel_url',$insert_channel_url_arr);
				
				//将下载地址存储到reids中
				$this->saveRedis($channel_id, $package_name, $insert_download_url);
				
				$coo_url_arr[] = $insert_coo_url;
			}
			$re_arr['status'] = 1;
			//$re_arr['exec_cmd'] = $exec_cmd_arr;
			$re_arr['coo_url'] = $coo_url_arr;
			echo json_encode($re_arr);
			return false;
		}
	}
	
	//服务器安装文件同步功能
	function rsyncAction(){
		$re_arr = array();
		$channel_id = trim($_POST['channel_id']);
		
		$package_model = D('package');
		//获取推广渠道的信息
		$channel_info = $package_model->getChannelListInfo($channel_id);
		if(empty($channel_info)){
			$re_arr['status'] = 2;
			echo json_encode($re_arr);
			return false;
		}
		if($channel_info['user_id'] != $this->user_info['user_id']){
			$re_arr['status'] = 3;
			echo json_encode($re_arr);
			return false;
		}
		
		$channel_sub = $channel_info['channel_sub'];
		
		$channel_country_num = $channel_info['channel_area'];
		//获取国家的配置信息
		
		$channel_country_info = $package_model->getChannelCountryByNum($channel_country_num);
		
		$rsync_sh_path = trim($channel_country_info['rsync_sh_path']);
		$market_domain = $channel_country_info['market_domain'];
		if(empty($rsync_sh_path)){
			$re_arr['status'] = 4;
			echo json_encode($re_arr);
			return false;
		}
		
		//定义要同步的安装包数组
		$rsync_market_arr = array();
		
		//查看这个渠道有多少捆绑软件
		$channel_url_arr = $package_model->getChannelUrlInfo($channel_id);
		//同步数据，和更新redis缓存
		foreach ($channel_url_arr as $kcu=>$vcu){
			$channel_package_name = $vcu['package_name'];
			$channel_download_url = $vcu['download_url'];
			
			$new_download_url = str_replace(C('package_default_domain'), $market_domain, $channel_download_url);
			if(strpos($channel_download_url,C('package_default_domain')) !== false){
				$rsync_path = str_replace(C('package_default_domain'),'',$channel_download_url);
				if(!empty($rsync_path)){
					$rsync_market_arr[] = $rsync_path;
				}
			}
			$update_domain_sql = "update channel_url set download_url='{$new_download_url}' where channel_id='{$channel_id}' and package_name='{$channel_package_name}'";
			$package_model->db->execute($update_domain_sql);
			$this->saveRedis($channel_id, $channel_package_name, $new_download_url);
		}
		
		if(empty($rsync_market_arr)){
			$re_arr['status'] = 4;
			echo json_encode($re_arr);
			return false;
		}
		
		$market_args = implode(' ',$rsync_market_arr);
		$rsync_sh_cmd = "$rsync_sh_path '{$market_args}' '{$channel_sub}' >> /tmp/package_rsync.log";

		@exec($rsync_sh_cmd);
		
		$re_arr['status'] = 1;
		echo json_encode($re_arr);
		return true;
	}
	
	
	//将渠道号的下载地址存储到redis中
	function saveRedis($channel_id,$pkg,$download_url){
		$redis = redis();
		//定义key的规则
		$key = "package_".md5($channel_id.'#'.$pkg);
		$redis->set($key,$download_url);
		$redis->expire($key,86400*30);  # 设置30天后过期
	}
}